package com.example.elderlycaresystem.interceptor;

import com.example.elderlycaresystem.util.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录接口和注册接口不需要验证Token
        if (request.getRequestURI().contains("/login") || request.getRequestURI().contains("/register")) {
            return true;
        }

        // 从请求头中获取Token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            if (JwtTokenUtil.validateToken(token)) {
                return true;
            }
        }

        // Token验证失败
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized: Invalid or expired token");
        return false;
    }
}